//
//  BaseCollectionViewDelegateProxy.m
//  mobile
//
//  Created by Demi on 16/03/2017.
//  Copyright © 2017 azazie. All rights reserved.
//

#import "BaseCollectionViewDelegateProxy.h"


#import <ReactiveObjC/ReactiveObjC.h>

@interface BaseCollectionViewDelegateProxy ()

@property (nonatomic, assign) Class cellClass;
@property (nonatomic, weak) UICollectionView *collectionView;

@end

@implementation BaseCollectionViewDelegateProxy

- (instancetype)initWithCellClass:(Class)cellClass collectionView:(nonnull __kindof UICollectionView *)collectionView
{
    self = [super init];
    if (self)
    {
        _cellClass = cellClass;
        _collectionView = collectionView;
        
        [collectionView registerClass:cellClass forCellWithReuseIdentifier:NSStringFromClass(cellClass)];
        
        collectionView.delegate = self;
        collectionView.dataSource = self;
        
        @weakify(self);
        [[RACObserve(self, items) skip:1] subscribeNext:^(id x){
            @strongify(self);
            [self.collectionView reloadData];
        }];
    }
    return self;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.items.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass(self.cellClass) forIndexPath:indexPath];
    
    self.cellBlock(self.items[indexPath.item], indexPath.item, cell);
    
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.cellSizingBlock)
    {
        return self.cellSizingBlock(self.items[indexPath.item], indexPath.item);
    }
    return [(UICollectionViewFlowLayout *)collectionViewLayout itemSize];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
}

@end
